import React, {useEffect, useRef, useState} from 'react';
import {View,StyleSheet,Button,PermissionsAndroid} from 'react-native';
import { WebView } from 'react-native-webview';
import {useHeaderHeight} from '@react-navigation/elements';
import {ThemeColor} from '../utils/common';
import {useNavigation} from '@react-navigation/native';
import {useAppStore} from '../store/useAppStore';
import store from 'react-native-simple-store'
let source = 'file:///android_asset/dist/index.html'

const messageObj = {
    "account": "0x15AfcD77E2d8a2b7F046b76C48AE0DA5681Efa76",
    "pubKey": "0x043df11e21e8e7e8776034d61d26a9c333252dd9d8790936d89fd34b0f3e260e8c421f540c9fc30ed029d54e4df821be88fed9b350814192c5f84075c5db6e0d90",
    "serviceId": "alipayService",
    "taskId": "sesameScoreTask"
}

const Auth = ()=>{

    const headerHeight = useHeaderHeight()
    const webRef = useRef(null)
    const navigation = useNavigation()
    const {appState:{ethShare},updateAppState} = useAppStore()

    useEffect(()=>{

        messageObj.account = ethShare.account.address
        messageObj.pubKey = ethShare.publicKey
        // console.log(messageObj);

        openWeb()
    },[])

    const openWeb = async ()=>{
        const key = 'android.permission.WRITE_EXTERNAL_STORAGE'
        const grant = await PermissionsAndroid.check('android.permission.WRITE_EXTERNAL_STORAGE')
        console.log(grant);
        if(grant){

        }else{
            const grant = PermissionsAndroid.request(key)

        }
    }



    return (
        <View style={[styles.container,{paddingTop:headerHeight}]}>
            <WebView
                ref={ref=>{
                    webRef.current = ref
                }}
                originWhitelist={['*']}
                source={{uri:source} }
                allowFileAccess={true}
                automaticallyAdjustContentInsets={true}
                domStorageEnabled={true}
                allowUniversalAccessFromFileURLs={true}
                allowFileAccessFromFileURLs={true}
                renderError={null}
                onLoadEnd={()=>{
                    const message = JSON.stringify(messageObj)
                    console.log('load end:',typeof message);
                    webRef.current.postMessage(message)
                }}
                //RN端接收消息
                onMessage={(e ) => {
                    const data = e.nativeEvent.data
                    console.log('Message received from JS: ',  data);
                    const obj = JSON.parse(  JSON.parse( data.trim()) )
                    // console.log(typeof obj);
                    // console.log(obj);
                    if(data.includes('hash')){
                        store.save('authHash',obj.hash)
                        updateAppState({
                            authHash:obj.hash
                        })
                        navigation.goBack()
                    }


                }}
            />

        </View>

    )
}

export default Auth

const styles = StyleSheet.create({
    container:{
        flex:1, backgroundColor:ThemeColor.theme
    }
})
